package cn.org.donald.framework.util;

import cn.org.donald.framework.constant.FileConstant;
import cn.org.donald.framework.constant.InfoConstant;
import cn.org.donald.framework.handler.ServiceException;
import cn.org.donald.framework.pojo.dto.UploadResult;
import org.springframework.http.HttpStatus;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.regex.Matcher;

/**
 * File util
 * @author ： Donald
 * @since ： 2020/10/24 13:57
 */
public class FileUtil {

    /**
     * File separator, use this separator because not every file path of operation system are the same.
     */
    public static String separator = Matcher.quoteReplacement(File.separator);

    /**
     * Get suffix of the file name.
     * @return string
     */
    public static String getSuffixName(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * Create a new file name
     * @param originFileName origin file name
     * @return A string of random uuid
     */
    public static String getNewFileName(String originFileName){
        return UUID.randomUUID() + getSuffixName(originFileName);
    }

    /**
     * Upload file util.
     * @param multipartFile multipart file.
     * @param group A group name of the server file path.
     * @return An entity which is result of the uploading.
     */
    public static UploadResult upload(MultipartFile multipartFile, String group){
        String originalFilename = multipartFile.getOriginalFilename();
        String newFileName = getNewFileName(originalFilename);
        String realPath = FileConstant.FILE_PATH_UPLOAD + group + separator + newFileName;
        try {
            //新建文件对象
            File file = new File(realPath);
            if (!file.getParentFile().exists()){
                boolean mkdirs = file.getParentFile().mkdirs();
                if (!mkdirs) throw new ServiceException(HttpStatus.INTERNAL_SERVER_ERROR.value(), InfoConstant.UPLOAD_FILE_FAIL);
            }
            multipartFile.transferTo(file);
        }catch (IOException e){
            throw new ServiceException(HttpStatus.INTERNAL_SERVER_ERROR.value(), InfoConstant.MKDIR_FAIL);
        }
        UploadResult uploadResult = new UploadResult();
        uploadResult.setUrl(FileConstant.FILE_PATH_REQUEST + group + separator + newFileName);
        uploadResult.setSuccess(true);
        return uploadResult;
    }


}
